import type { ResourceStatisticsIP } from '@/apis/model/dashboard'
import Decimal from 'decimal.js'
import {
  getStatisticAppComputeApi,
  getStatisticRegionApi,
} from '@/apis/modules/dashboard'
import { useApplication } from './useListData'

export interface StatisticsModel {
  allocated: number
  allocation_rate: string
  total?: number
  region_name?: string
  region_id?: string
  app_name?: string
  real_allocated?: number
  real_allocated_rate?: string
}

export interface IStatisticsData {
  cup_allocations: StatisticsModel[]
  memory_allocations: StatisticsModel[]
  storage_allocations: StatisticsModel[]
  region_baremetal_list: StatisticsModel[]
  cpuTotalData?: StatisticsModel
  memoryTotalData?: StatisticsModel
  storageTotalData?: StatisticsModel
  bakemeatsTotalData?: StatisticsModel
}

export interface IResourceModel {
  bandWidthID?: string
  subtitle: string
  list?: StatisticsModel[]
  totalData?: StatisticsModel
}

export interface HomeTotalData {
  title: string
  region_id: string
  ipList?: IResourceModel[]
  list?: IResourceModel[]
  bandWidthList?: IResourceModel[]
}

export function useStatistic(options?: { immeditae?: boolean }) {
  const opts = {
    ...{
      immediate: true,
    },
    ...options,
  }

  const regionsID = ref()

  const { allRegionOptions } = useRegions({
    after: async (v) => {
      if (v && v?.length) {
        regionsID.value = v?.[0].id
      }
    },
  })
  const { applicationOptions, bandWidthDataList, bandWidthOptions }
    = useApplication()

  const loading = ref<boolean>(false)
  const statisticsData = reactive<IStatisticsData>({
    cup_allocations: [],
    memory_allocations: [],
    storage_allocations: [],
    region_baremetal_list: [],
  })

  /** 首页的 ip 和带宽 */
  const homeTotalData = ref<HomeTotalData[]>([])

  /** 资源的总的IP 和带宽 */
  const resourceTotalIpData = ref<ResourceStatisticsIP>([])
  const resourceTotalBandWidthData = ref<ResourceStatisticsIP>([])

  const mapData = (data: any[], type?: string) => {
    return data?.map((item) => {
      const total
        = type && type === 'bandWidth'
          ? bandWidthDataList.value?.find(
            bandWidth => bandWidth.id === item.bandwidth_type,
          )?.value
          : item.total
      return {
        region_name: getOptionLabel(item.region_id, allRegionOptions.value),
        region_id: item.region_id,
        total,
        allocated: item.assign ?? item.instance_assign,
        allocation_rate: total
          ? Decimal.div(
              Number(item.assign ?? item.instance_assign),
              Number(total),
            )
              .mul(100)
              .toFixed(2)
          : '0',
        real_allocated: item?.real_assign || 0,
        real_allocated_rate:
          item?.real_assign && total
            ? Decimal.div(Number(item?.real_assign), Number(total))
                .mul(100)
                .toFixed(2)
            : '0',
      }
    })
  }

  /** 获取同一区域下的数据 */
  const getCommonRegion = (data: any[]) => {
    const groupedByRegion = data?.reduce((acc, item) => {
      if (!acc[item.region_id]) {
        acc[item.region_id] = []
      }
      acc[item.region_id].push(item)
      return acc
    }, {})
    return groupedByRegion
  }

  /** 处理 ip/带宽数据 */
  const handleListData = (data: any[]) => {
    const groupedByType = getCommonRegion(data)

    const result = Object.keys(groupedByType).map(key => ({
      title: getOptionLabel(key, allRegionOptions.value),
      region_id: key,
      list: groupedByType[key]?.map((item: any) => {
        return {
          subtitle: getOptionLabel(
            item?.bandwidth_type,
            bandWidthOptions.value,
          ),

          totalData: {
            total: item?.total,
            allocated: item?.assign,
            allocation_rate: item?.total
              ? Decimal.div(item?.assign, item?.total).mul(100).toFixed(2)
              : '0',
          },
        }
      }),
    }))
    return result
  }

  /** 将同一区域下的 ip 和带宽归类 */
  function mergeArraysKeepingLists(
    arr1: HomeTotalData[],
    arr2: HomeTotalData[],
  ) {
    // 创建一个map来存储每个region_id及其对应的原始列表
    const combinedArray: any[] = []
    const map = new Map()

    // 将第一个数组的元素添加到map中
    arr1.forEach((item: HomeTotalData) => {
      if (!map.has(item.region_id)) {
        map.set(item.region_id, {
          region_id: item.region_id,
          title: item.title,
          ipList: item.list,
        })
      }
    })

    // 将第二个数组的元素也添加到map中，如果存在相同的region_id，则将带宽数据存进去
    arr2.forEach((item) => {
      //  debugger
      if (!map.has(item.region_id)) {
        map.set(item.region_id, {
          region_id: item.region_id,
          title: item.title,
          bandWidthList: item.list,
        })
      } else {
        map.set(item.region_id, {
          ...map.get(item.region_id),
          bandWidthList: item.list,
        })
      }
    })

    // 将map中的值转换为数组形式并返回
    map.forEach((value) => {
      combinedArray.push(value)
    })
    return combinedArray
  }

  /** 显示所有的带宽和 ip ,没有分配的补0 */
  const handleFillData = (currentList: any) => {
    const list = bandWidthDataList.value?.map((item) => {
      const exitData = currentList?.find(
        (curItem: any) =>
          item.id === curItem.bandwidth_type
          && item.region_id === curItem.region_id,
      )
      return {
        region_id: item.region_id,
        bandwidth_type: item.id,
        total: item.value,
        assign: exitData ? exitData?.assign : 0,
      }
    })

    return list
  }

  /** 按照区域 id 排序 */
  function sortRegionId(data: any) {
    const sortedAsc = [...data].sort((a, b) => a.region_id - b.region_id)
    return sortedAsc
  }

  /** 首页汇总统计 */
  async function getTotalStatistic() {
    loading.value = true
    getStatisticRegionApi()
      .then((res) => {
        statisticsData.cup_allocations = mapData(
          sortRegionId(res.region_cpu_list || []),
        )
        statisticsData.memory_allocations = mapData(
          sortRegionId(res.region_memory_list || []),
        )
        statisticsData.storage_allocations = mapData(
          sortRegionId(res.region_storage_list || []),
        )
        statisticsData.region_baremetal_list = mapData(
          sortRegionId(res.region_baremetal_list || []),
        )
        resourceTotalIpData.value = res.region_ip_list as ResourceStatisticsIP
        resourceTotalBandWidthData.value = handleFillData(
          res.region_bandwidth_type_list,
        ) as ResourceStatisticsIP

        const IpData = handleListData(res.region_ip_list || [])
        const bandWidthData = handleListData(
          handleFillData(res.region_bandwidth_type_list || []) || [],
        )
        homeTotalData.value = mergeArraysKeepingLists(IpData, bandWidthData)
      })
      .finally(() => {
        loading.value = false
      })
  }
  /** 过滤区域下的应用 */
  const handleApp = (data?: any[], total?: number) => {
    const list = data
      ?.filter(item => item.region_id === regionsID.value)
      ?.map((item) => {
        return {
          app_id: item.app_id,
          app_name: getOptionLabel(item.app_id, applicationOptions.value),
          allocated: item?.assign || 0,
          allocation_rate: total
            ? Decimal.div(Number(item?.assign || 0), total)
                .mul(100)
                .toFixed(2)
            : '0',
        }
      })

    return list as StatisticsModel[]
  }

  /** 按照带宽分类 */
  const handleCommonBandWith = (data?: any[]) => {
    const groupedByType = data?.reduce((acc, item) => {
      if (!acc[item.bandwidth_type]) {
        acc[item.bandwidth_type] = []
      }
      acc[item.bandwidth_type].push(item)
      return acc
    }, {})
    return groupedByType
  }

  /** 过滤云计算资源的 ip 和带宽 */
  /** dashData 首页总统计数据 */
  const handleFilterApp = (appData?: any[], dashData?: any[]) => {
    /** 同一区域、同一带宽下的资源数据 */
    const groupedByType = handleCommonBandWith(
      dashData?.filter(item => item.region_id === regionsID.value),
    )
    /** 同一区域、同一带宽下的应用 */
    const newAppData = handleCommonBandWith(
      appData?.filter(item => item.region_id === regionsID.value),
    )

    /** 获取同一带宽和区域下的总 ip 和带宽 */
    const totalResourceData = Object.keys(groupedByType).map((key) => {
      /** 总的 ip 和带宽 */
      const currentItem = groupedByType[key]?.reduce(
        (acc: any, cur: any) => {
          const total = Decimal.sum(acc.total, cur.total).toNumber()
          const allocated = Decimal.sum(acc.assign, cur.assign).toNumber()
          const totalData = {
            total,
            allocated,
            allocation_rate: total
              ? Decimal.div(allocated, total).mul(100).toFixed(2)
              : '0',
          }
          return totalData
        },
        { total: 0, assign: 0 },
      )

      const data = {
        bandWidthID: key,
        subtitle: getOptionLabel(key, bandWidthOptions.value),
        list: newAppData[key]?.map((item: any, index: number) => {
          return {
            app_id: item.app_id,
            app_name: getOptionLabel(item.app_id, applicationOptions.value),
            allocated: item?.assign || 0,
            allocation_rate: currentItem?.total
              ? Decimal.div(Number(item?.assign || 0), currentItem?.total)
                  .mul(100)
                  .toFixed(2)
              : '0',
          }
        }),
        totalData: currentItem,
      }

      // const sum = (data?.list||[])?.reduce((acc: any, item: any, index: number) => {
      //   if (index < data?.list?.length - 1) {
      //     return acc + Number(item.allocation_rate)
      //   }
      //   return acc
      // }, 0)

      // data?.list?.length&&( data!.list[data?.list?.length - 1]!.allocation_rate = currentItem?.total)
      //   ? Decimal.sub(Number(currentItem?.allocation_rate), sum).toFixed(2)
      //   : '0'
      return data
    })

    return totalResourceData
  }

  /** 云计算资源 */
  const resourceLoading = ref<boolean>(false)
  const resourceData = ref()
  const resourceStatistics = reactive<IStatisticsData>({
    cup_allocations: [],
    memory_allocations: [],
    storage_allocations: [],
    region_baremetal_list: [],
  })
  /** 资源 ip 数据和带宽 */
  const resourceIpData = ref<IResourceModel[]>([])

  const resourceBandWidthData = ref<IResourceModel[]>([])

  function getComputedResource() {
    resourceLoading.value = true
    getStatisticAppComputeApi()
      .then((res) => {
        resourceData.value = res
      })
      .finally(() => {
        resourceLoading.value = false
      })
  }

  const handleTotalData = (data: any) => {
    const totalData = data?.find(
      (item: StatisticsModel) => item.region_id === regionsID.value,
    )
    return totalData
  }

  watchEffect(() => {
    if (regionsID.value) {
      resourceStatistics.cpuTotalData = handleTotalData(
        statisticsData.cup_allocations || [],
      )
      resourceStatistics.memoryTotalData = handleTotalData(
        statisticsData.memory_allocations || [],
      )
      resourceStatistics.storageTotalData = handleTotalData(
        statisticsData.storage_allocations || [],
      )
      resourceStatistics.bakemeatsTotalData = handleTotalData(
        statisticsData.region_baremetal_list || [],
      )
      resourceStatistics.cup_allocations = handleApp(
        resourceData.value?.app_cpu_list || [],
        resourceStatistics.cpuTotalData?.total || 0,
      )
      resourceStatistics.memory_allocations = handleApp(
        resourceData.value?.app_memory_list || [],
        resourceStatistics.memoryTotalData?.total || 0,
      )
      resourceStatistics.storage_allocations = handleApp(
        resourceData.value?.app_storage_list || [],
        resourceStatistics.storageTotalData?.total || 0,
      )
      resourceStatistics.region_baremetal_list = handleApp(
        resourceData.value?.app_baremetal_list || [],
        resourceStatistics.bakemeatsTotalData?.total || 0,
      )
      resourceIpData.value = handleFilterApp(
        resourceData.value?.app_ip_list || [],
        resourceTotalIpData.value,
      )
      resourceBandWidthData.value = handleFilterApp(
        resourceData.value?.app_bandwidth_type_list || [],
        resourceTotalBandWidthData.value,
      )
    }
  })

  onMounted(() => {
    if (opts?.immediate) {
      getTotalStatistic()
    }
  })

  return {
    loading,
    getTotalStatistic,
    statisticsData,
    homeTotalData,
    getComputedResource,
    regionsID,
    resourceLoading,
    allRegionOptions,
    resourceStatistics,
    resourceIpData,
    resourceBandWidthData,
  }
}
